import React from 'react';
import { Modal, Form, Select, notification } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import ImageUpload from '@/components/ImageUpload';
import { addSchedulest, schedulesList } from '@/services/api';
import { SIZE, PAGE } from '@/utils/constant';

interface props {
  onClose: () => void;
  dispatch: any;
  clasesData: any;
}

interface UserFormProps extends FormComponentProps {
  ref: any;
  clasesData: any;
}

const ref: any = React.createRef();
const { Item } = Form;
const MyForm = Form.create<UserFormProps>()(
  ({ form: { getFieldDecorator, setFieldsValue }, clasesData }: any) => {
    const formItemLayout = {
      labelCol: {
        xs: { span: 4, offset: 4 },
      },
      wrapperCol: {
        sm: { span: 8 },
      },
    };
    // 这些是可选的， 目前只用得到 imageIds， [1,2,3,3,4]
    const handlerChangeImgIds = (imageIds: any) => {
      imageIds.length
        ? setFieldsValue({ image_id: Number(imageIds.join()) })
        : setFieldsValue({ image_id: undefined });
    };
    return (
      <Form layout="horizontal" {...formItemLayout}>
        <Item label="班级">
          {getFieldDecorator('clase_id', {
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select
              placeholder="请选择"
              allowClear
              showSearch
              filterOption={(input: any, option: any) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {clasesData.map((item: any) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Item>
        <Item label="课程表">
          {getFieldDecorator('image_id', {
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <ImageUpload
              // ref={ref1}
              imageLength={1}
              handlerChangeImgIds={handlerChangeImgIds}
            />,
          )}
        </Item>
      </Form>
    );
  },
);

const AddScheduleModal = ({ onClose, dispatch, clasesData }: props) => {
  return (
    <Modal
      visible
      onCancel={onClose}
      maskClosable={false}
      title="新增课程表"
      onOk={() => {
        ref.current.validateFields({ first: true }, (err: any, val: any) => {
          const newValue = {
            ...val,
          };
          delete newValue.student;
          if (!err) {
            delete newValue.clase;
            delete newValue.image;

            addSchedulest(newValue).then((resp: any) => {
              if (resp.status === 'success') {
                notification.success({ message: '课程表新增成功' });
                onClose();
                dispatch({
                  type: 'OPEN_LOADING',
                });
                schedulesList({ page: PAGE, size: SIZE })
                  .then((res: any) => {
                    if (res.status === 'success') {
                      dispatch({
                        type: 'GET_DATA',
                        payload: res.data.data,
                      });
                      dispatch({
                        type: 'CHANGE_PAGINATION',
                        payload: {
                          current: PAGE,
                          pageSize: SIZE,
                          total: res.data.meta.total,
                        },
                      });
                    }
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  })
                  .catch(() => {
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  });
              }
            });
          }
        });
      }}
    >
      <MyForm ref={ref} clasesData={clasesData} />
    </Modal>
  );
};

export default AddScheduleModal;
